package com.pattern.prototype.deepclone;

import java.io.*;

/**
 * @author 冯志立
 * @create 2019-10-19 10:59
 */
public class DeepProtoType implements Serializable, Cloneable {
    private String name;
    public DeepCloneableTarget deepCloneableTarget; //引用类型

    public DeepProtoType() {
        super();
    }

    //深拷贝，方式1，使用clone（）方法
    @Override
    public Object clone() throws CloneNotSupportedException {
        Object deep = null;
        //这里完成对基本类型和string的克隆
        deep = super.clone();
        //对引用类型单独进行处理
        DeepProtoType deepProtoType = (DeepProtoType) deep;
        DeepProtoType clone = (DeepProtoType) deepProtoType.deepCloneableTarget.clone();
        return deep;
    }

    //深拷贝，方式2  通过对象的序列化实现（推荐）
    //成员变量在序列化时会重新创建而不是传引用，以此实现深拷贝
    public Object deepClone() {
        //创建流对象
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        try {
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            DeepProtoType copyObj = (DeepProtoType) ois.readObject();
            return copyObj;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            //关闭流
            try {
                bos.close();
                oos.close();
                bis.close();
                ois.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }


        }
    }
